#include <string>
#include <iostream>
#include <cstdlib>
#include <time.h>

#include "authenticate.h"
#include "query.h"

using namespace std;

int AuthenticateUser(string Email)
{
string IsMember="-1";
bool IsAuthenticated=false;
int ID;

/// String to hold the query to check if the user is in the system
string GetUserIDQuery="SELECT ID FROM Users WHERE Email='";
GetUserIDQuery+=Email;
GetUserIDQuery+="';";

///Execute the query
Query GetUserID(GetUserIDQuery);
GetUserID.Execute();

///Get the query results
string IDString=GetUserID.GetLastElementReturned();
ID=atoi(IDString.c_str());


if(ID<=0)///ID<=0 means the user isn't an active user yet or isnt a user at all
	{
	/// Check if the user has a project assigned yet not registered
	string IsNewUserQuery="select exists(select 1 from NewUsers where Email='";
	IsNewUserQuery+=Email;
	IsNewUserQuery+="');";
	
	Query IsNewUser(IsNewUserQuery);
	IsNewUser.Execute();
	int IsNew=atoi(IsNewUser.GetLastElementReturned().c_str());

	if(IsNew==1)//check if is a new user, project assigned to him by manager yet it is his first time login, if so return NEW_USER, else he is definitely not in the system=> return -1
		{
			//authenticate
			return NEW_USER;
		}
	else
		return NOT_A_USER;
	}
else
	{
	//Update the Users table with the new last seen date for the user
	char TimeDate[20];
	time_t t=time(NULL);
	strftime(TimeDate,20,"%Y-%m-%d %H:%M:%S",localtime(&t));
	string UpdateLastSeenQuery="UPDATE Users SET LastSeen='";
	UpdateLastSeenQuery+=TimeDate;
	UpdateLastSeenQuery+="' WHERE ID='";
	UpdateLastSeenQuery+=IDString;
	UpdateLastSeenQuery+="'";
//	SQL_query(query);
	Query UpdateLastSeen(UpdateLastSeenQuery);
	UpdateLastSeen.Execute();
	//NEW_USER will come back here to be authenticated after registering his name else we need to authenticate current user;
	//TODO: write the authentication function
	IsAuthenticated=true;
	return ID;
	}
}

bool IsManager(string Email)
{
///Build query to check if user is manager
string CheckIsManagerQuery="SELECT * FROM Managers LEFT JOIN Users ON Users.ID=Managers.ID WHERE Users.Email='";
CheckIsManagerQuery+=Email;
CheckIsManagerQuery+="';";

///Execute query
Query CheckIsManager(CheckIsManagerQuery);
CheckIsManager.Execute();

string IsManagerTemp=CheckIsManager.GetLastElementReturned();

//Check if manager
if(atoi(IsManagerTemp.c_str())>0)
	return true;
	
return false;
}
